import java.util.*;
class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val  , TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        //层序遍历,二维数组 每一个放一层，要计数
        List<List<Integer>> list = new ArrayList<>();
        if(root == null){
            return list;
        }
        Queue<TreeNode> qu = new LinkedList<>();
        qu.offer(root);
        while(!qu.isEmpty()){
            int size = qu.size();
            List<Integer> temp = new ArrayList<>();
            while(size>0){
                //存每一层的根结点
                TreeNode cur = qu.poll();
                size--;
                temp.add(cur.val);
                //存左右子结点
                if(cur.left != null){
                    qu.offer(cur.left);
                }
                if(cur.right != null){
                    qu.offer(cur.right);
                }
            }
            list.add(temp);
        }
        return list;
    }
}
